#include "gfx_image.h"

#include <stdio.h>

static Map *_Images;

void gfx_image_init(void)
{
    _Images = map_new();
}

void gfx_image_exit(void)
{
    // Free all images
    while(map_size(_Images))
    {
        MapPair *pair = map_iterator(_Images, 0);
        gfx_image_unload(pair->key);
    }
    map_delete(_Images);
}

int _gfx_image_load_properties(const char *filename, GFX_Image *image)
{
    char cfgFileName[256];
    char imgName[256];
    sprintf(cfgFileName, "%s.txt", filename);
    FILE *fp = fopen(cfgFileName, "r");
    if(fp == 0) { return -1; }

    fscanf(fp, "%s %d %d %d %d", imgName, &image->rows, &image->columns, &image->xoffset, &image->yoffset);
    image->name = mem_strdup(imgName);
    int r = 0, g = 0, b = 0;
    fscanf(fp, "%d %d %d", &r, &g, &b);
    SDL_SetColorKey(image->image, SDL_SRCCOLORKEY, SDL_MapRGB(((SDL_Surface*)(image->image))->format, r, g, b));
    fclose(fp);
    return 0;
}

int gfx_image_load(const char *filename)
{
    SDL_Surface *image_sdl = SDL_LoadBMP(filename);
    if(image_sdl == 0)
    {
        return -1;
    }
    GFX_Image *image = mem_allocate(sizeof(GFX_Image));
    image->width = image_sdl->w;
    image->height = image_sdl->h;
    image->image = image_sdl;
    if(_gfx_image_load_properties(filename, image) == -1)
    {
        SDL_FreeSurface(image_sdl);
        mem_free(image->name);
        mem_free(image);
        return -1;
    }
    map_insert (_Images,image->name, image );
    return 0;
}

int gfx_image_unload(const char *name)
{
    GFX_Image *image = map_lookup(_Images, name);
    if(image == 0) { return -1; }
    SDL_FreeSurface(image->image);
    mem_free(image->name);
    mem_free(image);
    map_remove(_Images, name);
    return 0;
}

GFX_Image* gfx_image_get(const char *name)
{
    GFX_Image *image = map_lookup(_Images, name);
    return image;
}

MapPair* gfx_image_iterator(MapPair *pair)
{
    return map_iterator(_Images, pair);
}
